package Aleehot100;

/**
 * ClassName: c027
 * Package: Aleehot100
 * Description: 合并两个有序链表
 *
 * @Author BCXJ
 * @Create 2025/6/13 20:31
 * @Version 1.0
 * @Since 1.0
 */
public class c027 {
    public static void main(String[] args) {
        ListNode listNode5 = new ListNode(5);

        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode4 = new ListNode(4);
        listNode1.next = listNode2;
        listNode2.next = listNode4;

        mergeTwoLists(listNode5, listNode1);

    }

    static class ListNode {
        int val;
        ListNode next;

        public ListNode(int val) {
            this.val = val;
            next = null;
        }
    }

    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null || list2 == null) {
            return list1 == null ? list2 : list1;
        }
        ListNode res = list1.val <= list2.val ? list1 : list2;
        ListNode cur1 = res.next;
        ListNode cur2 = res == list1 ? list2 : list1;
        ListNode pre = res;
        while(cur1 != null && cur2 != null) {
            if(cur1.val <= cur2.val) {
                pre.next = cur1;
                pre = cur1;
                cur1 = cur1.next;
            } else {
                pre.next = cur2;
                pre = cur2;
                cur2 = cur2.next;
            }
        }
        pre.next = cur1 != null ? cur1 : cur2;
        return res;
    }
}
